import Vue from 'vue';
import GlobalMixin from '@/mixins/global.mixin';
import * as lvtongFilters from '@/filters';
import { healthApis } from '@/api';
import { session } from '../storage';
import { formatConfig } from './format-config';

// Register global mixin
Vue.mixin(GlobalMixin);

// Register global filter functions
const filters = { ...lvtongFilters };
Object.keys(filters).forEach((key) => Vue.filter(key, filters[key]));

const plugin = async (
  { app, params: { site, newCompanyId }, query: { backHomeUrl, _homeUrl, _from }, store },
  inject,
) => {
  if (!newCompanyId || !site) {
    const _mounted = app.mounted;
    app.mounted = function () {
      this.error({ statusCode: 500, message: '缺少必要参数，请检查链接!' });
      _mounted && _mounted.call(this);
    };
    inject('siteConfig', {});
    return;
  }

  // 第三方对接过来，要回首页时，回指定的第三方首页
  // NOTE: backHomeUrl 是兼容历史版本
  _from && session.set('from', _from);
  (_homeUrl || backHomeUrl) && session.set('homeUrl', _homeUrl || backHomeUrl);

  // 保存到store里
  store.commit('app/setSite', site);
  store.commit('app/setNewCompanyId', newCompanyId);

  const res = await healthApis.getProfile({ data: { site }, loading: true });
  if (!res) {
    const _mounted = app.mounted;
    app.mounted = function () {
      this.error({ statusCode: 500, message: '未查询到相关单位信息，请检查链接' });
      _mounted && _mounted.call(this);
    };
    inject('siteConfig', {});
    return;
  }
  const config = formatConfig({ ...res, site, newCompanyId });
  inject('siteConfig', config);
};

export default plugin;
